package com.pick.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pick.admin.entity.SysUser;
import com.pick.admin.entity.SysUserRole;
import com.pick.admin.mapper.SysUserMapper;
import com.pick.admin.mapper.SysUserRoleMapper;
import com.pick.admin.service.SysUserService;
import com.pick.base.common.PageQuery;
import com.pick.base.constants.SystemConstants;
import com.pick.base.exception.BusinessException;
import com.pick.base.util.PasswordUtil;
import com.pick.base.utils.PasswordValidator;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 系统用户服务实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser getByUsername(String username) {
        return this.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
    }

    @Override
    public SysUser getByEmail(String email) {
        return this.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getEmail, email));
    }

    @Override
    public SysUser getByMobile(String mobile) {
        return this.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getMobile, mobile));
    }

    @Override
    public IPage<SysUser> pageUsers(PageQuery pageQuery) {
        Page<SysUser> page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        
        if (StrUtil.isNotBlank(pageQuery.getKeyword())) {
            wrapper.like(SysUser::getUsername, pageQuery.getKeyword())
                    .or().like(SysUser::getRealName, pageQuery.getKeyword())
                    .or().like(SysUser::getMobile, pageQuery.getKeyword())
                    .or().like(SysUser::getEmail, pageQuery.getKeyword());
        }
        
        if (StrUtil.isNotBlank(pageQuery.getOrderBy())) {
            if ("ASC".equalsIgnoreCase(pageQuery.getOrder())) {
                wrapper.orderByAsc(SysUser::getId);
            } else {
                wrapper.orderByDesc(SysUser::getId);
            }
        } else {
            wrapper.orderByDesc(SysUser::getCreateTime);
        }
        
        return this.page(page, wrapper);
    }

    @Override
    @Transactional
    public boolean createUser(SysUser user) {
        // 检查用户名是否已存在
        if (getByUsername(user.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 验证密码强度
        if (!PasswordValidator.isValid(user.getPassword())) {
            throw new BusinessException("密码不符合要求：" + PasswordValidator.getPasswordRequirements());
        }
        
        // 加密密码
        user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        user.setStatus(SystemConstants.UserStatus.ENABLED); // 默认启用
        
        return this.save(user);
    }

    @Override
    public boolean updateUser(SysUser user) {
        // 不允许修改密码
        user.setPassword(null);
        return this.updateById(user);
    }

    @Override
    @Transactional
    public boolean deleteUser(Long userId) {
        // 删除用户角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        
        // 删除用户
        return this.removeById(userId);
    }

    @Override
    public boolean resetPassword(Long userId, String newPassword) {
        // 验证密码强度
        if (!PasswordValidator.isValid(newPassword)) {
            throw new BusinessException("密码不符合要求：" + PasswordValidator.getPasswordRequirements());
        }
        
        SysUser user = new SysUser();
        user.setId(userId);
        user.setPassword(PasswordUtil.encrypt(newPassword));
        return this.updateById(user);
    }

    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        SysUser user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!PasswordUtil.verify(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        user.setPassword(PasswordUtil.encrypt(newPassword));
        return this.updateById(user);
    }

    @Override
    @Transactional
    public boolean assignRoles(Long userId, List<Long> roleIds) {
        // 删除原有角色
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        
        // 分配新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
        }
        
        return true;
    }

    @Override
    public List<String> getUserRoleCodes(Long userId) {
        return baseMapper.selectRoleCodesByUserId(userId);
    }

    @Override
    public List<String> getUserPermissionCodes(Long userId) {
        return baseMapper.selectPermissionCodesByUserId(userId);
    }
}